#include "mainwindow.h"

#include "ui_mainwindow.h"
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->frame_2->setVisible(false);
    ui->le_username->setPlaceholderText("username");
    ui->le_password->setPlaceholderText("password");
    setup_customplot(ui->customPlot);
}

void MainWindow::new_client()
{

    socket = server.nextPendingConnection();
    qDebug()<<"New client connetction from "<<socket->peerAddress().toString()<<":"<<socket->peerPort();
    connect(socket, SIGNAL(readyRead()),this,SLOT(read_client_data()));
    connect(socket, SIGNAL(disconnected()),this,SLOT(client_dis()));
    ui->lb_clientSock->setText(socket->peerAddress().toString()+":"+QString("%1").arg(socket->peerPort()));
}

void MainWindow::read_client_data()
{
    recvBuffer.append(socket->readAll());
    QDataStream recvStream(recvBuffer);
    recvStream.setVersion(QDataStream::Qt_4_6);
    qint32 packSize, datatype;
    while(recvBuffer.size() > sizeof(qint32) * 10)
    {
        for(int i = 0; i < 4; ++i)
        {
            qint32 m,n;
            recvStream >> m >> n;
            if(m != 0x7FFFFFFF || n != 0)
                qDebug("Head error!");
        }
        recvStream >> packSize >> datatype;
        qDebug() << "packSize:" << packSize << ", datatype:" << datatype;
        if(recvBuffer.size() >= packSize)
        {
            switch(datatype)
            {
            case 1:
            {
                Transfer t;
                recvStream >> t;
                ui->lb_R->setText(QString("%1 Ohm").arg(t.R));
                if(!t.img.isNull())
                {
                    ui->lb_pic->setPixmap(QPixmap::fromImage(t.img.scaled(ui->lb_pic->size(), Qt::KeepAspectRatio)));
                    ui->lb_timestamp->setText(t.timestamp.toString("yyyy/MM/dd hh:mm:ss"));
                }
                double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
                qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);

                ui->customPlot->graph(0)->addData(key, t.R);//添加数据1到曲线1
                //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
                //才能起到想要的效果，可以调整这两个值，观察显示的效果。
                ui->customPlot->graph(0)->removeDataBefore(key-8);

              //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
        //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围

                ui->customPlot->graph(0)->rescaleValueAxis();

                //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
                //就把8调整为比较大到值，比如要显示60秒，那就改成60。
                //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
                ui->customPlot->xAxis->setRange(key+0.25, 8, Qt::AlignRight);//设定x轴的范围
                ui->customPlot->replot();
                break;
            }
            case 2:
            {
                QString username, password;
                recvStream >> username >> password;
                outBlock.clear();
                QDataStream out(&outBlock, QIODevice::WriteOnly);
                out.setVersion(QDataStream::Qt_4_6);
                out << qint32(0x7FFFFFFF) << qint32(0)
                    << qint32(0x7FFFFFFF) << qint32(0)
                    << qint32(0x7FFFFFFF) << qint32(0)
                    << qint32(0x7FFFFFFF) << qint32(0)
                    << qint32(0) << qint32(2)
                    << (username == "ADMIN" && password == "ABC");
                out.device()->seek(sizeof(qint32)*8);
                out << outBlock.size();
                if(socket->write(outBlock) != outBlock.size())
                    qDebug() << "send auth result error!";
                break;
            }
            default:
                break;
            }
            recvBuffer.remove(0,packSize);
        }
        else break;
    }
}

void MainWindow::client_dis()
{
    qDebug()<<"Client " << socket->peerAddress().toString()<<":"<<socket->peerPort() <<" disconnected!";
    ui->lb_clientSock->setText("-");
    ui->lb_R->setText("-");
    ui->lb_pic->setText("*PICTURE*");
    ui->lb_timestamp->setText("-");
    recvBuffer.clear();
}

void MainWindow::setup_customplot(QCustomPlot *customPlot)
{
    //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
     //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
   //#endif
     //demoName = "Real Time Data Demo";

     // include this section to fully disable antialiasing for higher performance:
     /*
     customPlot->setNotAntialiasedElements(QCP::aeAll);
     QFont font;
     font.setStyleStrategy(QFont::NoAntialias);
     customPlot->xAxis->setTickLabelFont(font);
     customPlot->yAxis->setTickLabelFont(font);
     customPlot->legend->setFont(font);
     */
     customPlot->addGraph(); // blue line
     customPlot->graph(0)->setPen(QPen(Qt::blue));
     customPlot->graph(0)->setName("temp");
     //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
     //customPlot->graph(0)->setAntialiasedFill(false);
     //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


     customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
     customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
     customPlot->xAxis->setAutoTickStep(false);
     customPlot->xAxis->setTickStep(2);
     customPlot->axisRect()->setupFullAxesBox();

     // make left and bottom axes transfer their ranges to right and top axes:
     //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
     //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

     // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
     customPlot->legend->setVisible(false);
}

void MainWindow::plot_refresh()
{
        //if(t.R == 0)
            return;
    //key的单位是秒
        double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
        qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);

 //       ui->customPlot->graph(0)->addData(key, t.R);//添加数据1到曲线1
        //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
        //才能起到想要的效果，可以调整这两个值，观察显示的效果。
        ui->customPlot->graph(0)->removeDataBefore(key-8);

      //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
//也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围

        ui->customPlot->graph(0)->rescaleValueAxis();

        //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
        //就把8调整为比较大到值，比如要显示60秒，那就改成60。
        //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
        ui->customPlot->xAxis->setRange(key+0.25, 8, Qt::AlignRight);//设定x轴的范围
        ui->customPlot->replot();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    if(ui->le_username->text() == "ADMIN" && ui->le_password->text() == "123")
    {
        ui->frame->close();
        connect(&server,SIGNAL(newConnection()),this,SLOT(new_client()));
        server.listen(QHostAddress::Any, 2333);
        ui->lb_serverStatus->setText(QString("Listening on :%1").arg(server.serverPort()));
        recvBuffer.clear();
        //connect(&refresh_Timer, SIGNAL(timeout()), SLOT(plot_refresh()));
        refresh_Timer.start(200);
        ui->frame_2->setVisible(true);
    }
    else QMessageBox::warning(this, "Login Error!", "Username or password wrong, please retry!", "OK");
}
